Print lots of stars patterns


Posted by Christy on 2022-04-19

Description: Write a function named stars2 that accepts a number n and print the star patterns like below.

stars2(1)
*

stars2(3)
*
**
***
**
*

stars2(5)
*
**
***
****
*****
****
***
**
*

Answer:

function stars2(n) {
  for (let i = 1; i <= n; i++) {
    let star = "";
    for (let j = 1; j <= i; j++) {
      star += "*";
    }
    console.log(star);
  }

  for (let i = n - 1; i > 0; i--) {
    let star = "";
    for (let j = 1; j <= i; j++) {
      star += "*";
    }
    console.log(star);
  }
}

stars2(1);
stars2(3);
stars2(5);

Or here I wrap the repetition part as a star function

function star(i) {
  let result = "";
  for (let j = 1; j <= i; j++) {
    result += "*";
  }
  return result;
}

function stars2(n) {
  for (let i = 1; i <= n; i++) {
    console.log(star(i));
  }
  for (let i = n - 1; i > 0; i--) {
    console.log(star(i));
  }
}

stars2(1);
stars2(3);
stars2(5);









Related Posts

What Type of Laser Engraving Machine Should be Used for Stainless Steel Engraving?

What Type of Laser Engraving Machine Should be Used for Stainless Steel Engraving?

[FE301] React 基礎(Class component 版)先別急著學 React

[FE301] React 基礎(Class component 版)先別急著學 React

Day00 - CERN ROOT 教學 | 動機、這是什麼

Day00 - CERN ROOT 教學 | 動機、這是什麼


Comments